package ace.cmp.spring.data.jdbc.querydsl.core.impl;

import ace.cmp.spring.data.jdbc.querydsl.core.LogicDeleteHelper;
import ace.cmp.spring.data.jdbc.querydsl.core.annotations.LogicDelete;
import java.lang.reflect.Field;
import java.util.List;
import lombok.SneakyThrows;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.springframework.context.ApplicationContext;

/**
 * @author caspar
 * @date 2023/8/25 9:51
 */
public class LogicDeleteHelperImpl implements LogicDeleteHelper {
  private final ApplicationContext applicationContext;

  public LogicDeleteHelperImpl(ApplicationContext applicationContext) {
    this.applicationContext = applicationContext;
  }

  @Override
  @SneakyThrows
  public Object getLogicDeleteFieldValue(Object object) {
    if (object == null) {
      return null;
    }
    Field field = this.getLogicDeleteField(object.getClass());
    if (field == null) {
      return null;
    }
    return PropertyUtils.getProperty(object, field.getName());
  }

  @Override
  public <T> Field getLogicDeleteField(Class<T> entityType) {
    List<Field> fields = FieldUtils.getFieldsListWithAnnotation(entityType, LogicDelete.class);
    if (fields.size() > 1) {
      throw new RuntimeException("LogicDelete cannot more than 1");
    }
    if (CollectionUtils.isEmpty(fields)) {
      return null;
    }
    Field logicDeleteField = fields.get(0);
    return logicDeleteField;
  }
}
